<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Achievement as AchievementModel;
use addons\qingdongams\model\AchievementRecords;
use addons\qingdongams\model\Contract;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Flow;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\StaffDepartment;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\Receivables;
use addons\qingdongams\model\Event;
use addons\qingdongams\model\StaffTeam;
use addons\qingdongams\model\Workorder;
use think\Db;
use think\Exception;
/**
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
/**
 * 业绩管理接口
 */
class Achievement extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
        try{
            \think\Db::execute("SET @@sql_mode='';");
        }catch (Exception $e){

        }
    }
    //部门列表
    public function getDepartment()
    {
        $department = StaffDepartment::where([])->field('id,name')->select();
        $start = 2020;
        $end = date('Y');
        for ($start; $start <= $end; $start++) {
            if ($start == $end) {
                $years[] = [
                    'id' => $start,
                    'name' => $start . '年',
                    'selected' => 'selected'
                ];
            } else {
                $years[] = [
                    'id' => $start,
                    'name' => $start . '年',
                ];
            }
        }
        $department = array_merge([['id' => 0, 'name' => '全部']], $department);

        $this->success('请求成功', ['department' => $department, 'years' => $years]);
    }

    //获取员工业绩目标列表
    public function getStaffList()
    {
        $department_id = input('department_id');
        $year = input('year', date('Y'), 'intval');
        $status = input('status', 1);//1获客 2拜访 3业绩 4回款 5工单
        $where = [];
        if ($department_id) {
            $where['department_id'] = $department_id;
        }
        $where['status'] = 1;
        $staffModel = new Staff();
        $with = [ 'achievement' => function ($query) use ($year, $status) {
            $query->where(['year' => $year, 'status' => $status])->field('yeartarget,obj_id');
        }];
        if ($status == 1) {//获客
            $with['customer'] = function ($query) use ($year) {
                //客户
                $query->where(['createtime' => ['between', [strtotime($year . '-1-1'), strtotime($year . '-12-31')]]]);
            };
        } elseif ($status == 2) {//拜访
            $with['visit'] = function ($query) use ($year) {
                //订单签署日期
                $query->where(['createtime' => ['between', [strtotime($year . '-1-1'), strtotime($year . '-12-31')]]]);
            };
        } elseif ($status == 3) {//业绩
            $with['contract'] = function ($query) use ($year) {
                //订单签署日期
                $query->where(['order_date' => ['between', [$year . '-1-1', $year . '-12-31']]]);
            };
        } elseif ($status == 4) {//回款
            $with['receivables'] = function ($query) use ($year) {
                //回款日期
                $query->where(['return_time' => ['between', [$year . '-1-1', $year . '-12-31']]]);
            };
        } elseif ($status == 5) {//工单
            $with['workorder'] = function ($query) use ($year) {
                //回款日期
                $query->where(['createtime' => ['between', [strtotime($year . '-1-1'), strtotime($year . '-12-31')]]]);
            };
        }
        $staffs = $staffModel->where($where)->field('id,name,img,post')->with($with)->select();

        foreach ($staffs as $k => $v) {
            if (empty($v['achievement'])) {
                $v['achievement'] = ['yeartarget' => 0];
            }
            $v['ratio'] = getRatio($v['achieve'], $v['achievement']['yeartarget']);
            $staffs[$k] = $v;
        }

        $this->success('请求成功', $staffs);
    }

    //获取员工业绩目标详情
    public function getStaffDetail()
    {
        $staff_id = input('staff_id');
        $year = input('year', date('Y'), 'intval');
        $status = input('status', 1);//1获客 2拜访 3业绩 4回款 5工单
        $model = new AchievementModel();
        $achievement = $model->where([
            'obj_id' => $staff_id,
            'type' => 3,
            'year' => $year,
            'status' => $status
        ])->find();
        $achievement = $achievement ?? [];
        if ($achievement) {
            $achievement = $achievement->toArray();
        }
        $where = [];
        $startDate = date('Y-1-1');
        $endDate = date('Y-m-t');
        if ($status == 1) {//客户
            $where['createtime'] = ['between', [strtotime($startDate), strtotime($endDate) + 86400 - 1]];
            $where['create_staff_id'] = $staff_id;
            $moneys = Customer::where($where)
                ->field('count(*) as number,FROM_UNIXTIME(createtime,"%Y-%m") as month')
                ->group('month')->select();

        } elseif ($status == 2) {//拜访
            $where['actual_end_time'] = ['between', [strtotime($startDate), strtotime($endDate) + 86400 - 1]];
            $where['staff_id'] = $staff_id;
            $where['type'] = 3;
            $where['status'] = 2;
            $moneys = Event::where($where)->field('count(*) as number,FROM_UNIXTIME(actual_end_time,"%Y-%m") as month')
                ->group('month')->select();
        } elseif ($status == 3) {//订单
            $where['order_date'] = ['between', [$startDate, $endDate]];
            $where['check_status'] = 2;
            $where['owner_staff_id'] = $staff_id;
            $moneys = Contract::where($where)->group('month')
                ->field('sum(money) as number,`FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),"%Y-%m") `as month')
                ->select();
        } elseif ($status == 4) {//回款
            $where['return_time'] = ['between', [$startDate, $endDate]];
            $where['check_status'] = 2;
            $where['owner_staff_id'] = $staff_id;
            $moneys = Receivables::where($where)->group('month')
                ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),"%Y-%m") as month')
                ->select();
        } elseif ($status == 5) {
            $where['createtime'] = ['between', [strtotime($startDate), strtotime($endDate) + 86400 - 1]];
            $where['status'] = 3;
            $where['owner_staff_id'] = $staff_id;
            $moneys = Workorder::where($where)->group('month')
                ->field('count(*) as number,FROM_UNIXTIME(createtime,"%Y-%m") as month')
                ->select();
        }
        $moneys_list = [];
        foreach ($moneys as $v) {
            $moneys_list[$v['month']] = $v;
        }
        $total = ['money' => 0];
        foreach ($achievement as $k => $v) {
            if ($month = AchievementModel::getFieldMonth($k)) {
                $month = $year . '-' . $month;
                $achievement[$month] = isset($moneys_list[$month]) ? $moneys_list[$month]['number'] : 0;
                $total['money'] += $achievement[$month];
            }
        }
        //合计目标
        $total['achievement'] = isset($achievement['january']) ? ($achievement['january'] + $achievement['february'] + $achievement['march'] + $achievement['april'] + $achievement['may'] + $achievement['june'] + $achievement['july'] + $achievement['august'] + $achievement['september'] + $achievement['october'] + $achievement['november'] + $achievement['december']) : 0;

        //目标
        $achievement['yeartarget'] = $achievement['yeartarget'] ?? 0;
        $achievement['total_money'] = $total['money'];
        $achievement['surplus_money'] = $achievement['yeartarget'] - $achievement['total_money'];
        $achievement['total_achievement'] = $total['achievement'];

        $this->success('请求成功', $achievement);
    }


    //获取公司业绩目标
    public function getCompanyAchievement()
    {
        $year = input('year', date('Y'), 'intval');
        $status = input('status', 1);//1获客 2拜访 3业绩 4回款 5工单
        $model = new AchievementModel();
        $achievement = $model->where([
            'type' => 1,
            'year' => $year,
            'status' => $status
        ])->find();
        if (empty($achievement)) {
            $model->save(['type' => 1, 'year' => $year, 'status' => $status]);
            $achievement = $model->where(['type' => 1, 'year' => $year, 'status' => $status])->find();
        }
        $achievement = $achievement->toArray();

        $where = [
        ];
        $startDate = date('Y-1-1');
        $endDate = date('Y-m-t');

        if ($status == 1) {//客户
            $where['createtime'] = ['between', [strtotime($startDate), strtotime($endDate) + 86400 - 1]];
            $moneys = Customer::where($where)
                ->field('count(*) as number,FROM_UNIXTIME(createtime,"%Y-%m") as month')
                ->group('month')->select();

        } elseif ($status == 2) {//拜访
            $where['actual_end_time'] = ['between', [strtotime($startDate), strtotime($endDate) + 86400 - 1]];
            $where['type'] = 3;
            $where['status'] = 2;
            $moneys = Event::where($where)->field('count(*) as number,FROM_UNIXTIME(actual_end_time,"%Y-%m") as month')
                ->group('month')->select();
        } elseif ($status == 3) {//订单
            $where['order_date'] = ['between', [$startDate, $endDate]];
            $where['check_status'] = 2;
            $moneys = Contract::where($where)->group('month')
                ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(order_date),"%Y-%m") as month')
                ->select();
        } elseif ($status == 4) {//回款
            $where['return_time'] = ['between', [$startDate, $endDate]];
            $where['check_status'] = 2;
            $moneys = Receivables::where($where)->group('month')
                ->field('sum(money) as number,FROM_UNIXTIME(UNIX_TIMESTAMP(return_time),"%Y-%m") as month')
                ->select();
        }

        $moneys_list = [];
        foreach ($moneys as $v) {
            $moneys_list[$v['month']] = $v;
        }
        $total = ['money' => 0];
        foreach ($achievement as $k => $v) {
            if ($month = AchievementModel::getFieldMonth($k)) {
                $month = $year . '-' . $month;
                $achievement[$month] = isset($moneys_list[$month]) ? $moneys_list[$month]['number'] : 0;
                $total['money'] += $achievement[$month];
            }
        }
        //合计目标
        $total['achievement'] = isset($achievement['january']) ? ($achievement['january'] + $achievement['february'] + $achievement['march'] + $achievement['april'] + $achievement['may'] + $achievement['june'] + $achievement['july'] + $achievement['august'] + $achievement['september'] + $achievement['october'] + $achievement['november'] + $achievement['december']) : 0;

        //目标
        $achievement['yeartarget'] = $achievement['yeartarget'] ?? 0;
        $achievement['total_money'] = $total['money'];//合计业绩
        $achievement['surplus_money'] = $achievement['yeartarget'] - $achievement['total_money'];//剩余目标
        $achievement['total_achievement'] = $total['achievement'];//合计目标

        $this->success('请求成功', $achievement);
    }

    //修改目标
    public function addAchievement()
    {
        $type = input('type');//3个人 2团队 1公司
        $year = input('year', date('Y'), 'intval');
        $status = input('status', 1);//1获客 2拜访 3业绩 4回款
        $yeartarget = input('yeartarget');
        $ids = input('ids', 0);

        if ($type == 1) {
            $ids = 0;
        }
        $model = new AchievementModel();
        $ids = explode(',', $ids);
        $average = $yeartarget ? round($yeartarget / 12, 2) : 0;

        $save = [
            'yeartarget' => $yeartarget ?? 0,
            'january' => $average,
            'february' => $average,
            'march' => $average,
            'april' => $average,
            'may' => $average,
            'june' => $average,
            'july' => $average,
            'august' => $average,
            'september' => $average,
            'october' => $average,
            'november' => $average,
            'december' => $average,
        ];
        Db::startTrans();
        try {

            foreach ($ids as $id) {
                $row = $model->where(['type' => $type, 'year' => $year, 'obj_id' => $id, 'status' => $status])->find();
                if (empty($row)) {
                    $save['type'] = $type;
                    $save['year'] = $year;
                    $save['status'] = $status;
                    $save['obj_id'] = $id;
                    $save['createtime'] = time();
                    $save['updatetime'] = time();

                    $model->insert($save);
                } else {
                    $model = new AchievementModel();
                    $model->save($save, ['id' => $row['id']]);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('修改成功');
    }

    //员工 获取我的业绩目标详情
    public function getMyAchievementDetail()
    {

        $year = input('year', date('Y'), 'intval');
        $status = input('status', 1);//1销售（目标）2回款（目标）
        $type = input('type', 3);//3员工 2团队

        $model = new AchievementModel();
        $achievement = $model->where([
            'obj_id' => $this->auth->id,
            'type' => $type,
            'year' => $year,
            'status' => $status
        ])->find();
        $achievement = $achievement ?? [];
        if ($achievement) {
            $achievement = $achievement->toArray();
        }
        $achievement['yeartarget'] = $achievement['yeartarget'] ?? 0;


        $this->success('请求成功', $achievement);
    }

    //员工自己修改目标
    public function staffEditAchievement()
    {
        $type = input('type', 3);//3员工 2团队
        $year = input('year', date('Y'), 'intval');
        $status = input('status', 1);//1销售（目标）2回款（目标） 3 获客  4拜访
        $achievements = input('achievements/a');
        $flow_staff_ids = input('flow_staff_ids');

        $model = new AchievementRecords();
        $id = $this->auth->id;

        $update = [];
        if (isset($achievements['yeartarget'])) {
            $update['yeartarget'] = $achievements['yeartarget'] ?? 0;
        }

        $params = [
            'type' => $type,
            'year' => $year,
            'status' => $status,
            'obj_id' => $id,
            'yeartarget' => $update['yeartarget'],
            'january'       => $achievements['january'] ?? 0,
            'february'      => $achievements['february'] ?? 0,
            'march'         => $achievements['march'] ?? 0,
            'april'         => $achievements['april'] ?? 0,
            'june'          => $achievements['june'] ?? 0,
            'may'           => $achievements['may'] ?? 0,
            'july'          => $achievements['july'] ?? 0,
            'august'        => $achievements['august'] ?? 0,
            'september'     => $achievements['september'] ?? 0,
            'october'       => $achievements['october'] ?? 0,
            'november'      => $achievements['november'] ?? 0,
            'december'      => $achievements['december'] ?? 0,
            'flow_staff_ids' => $flow_staff_ids,
            'check_status' => 0,
            'owner_staff_id' => $id,
            'createtime' => time(),
            'updatetime' => time()
        ];

        Db::startTrans();
        try {

            $flow = Flow::getsteplist(Flow::ACHIEVEMENT_STATUS);
            $params['flow_id'] = $flow['flow_id'];
            $params['order_id'] = $flow['order_id'];

            if ($flow['status'] == 0) {//发起人自选
                if (empty($params['flow_staff_ids'])) {
                    throw new Exception('审批人必须选择');
                }
                $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
            } else {
                if (empty($flow['flow_staff_ids'])) {
                    throw new Exception('没有直属上级无法审批，请联系管理员！');
                }
                $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
            }

            if ($model->insert($params) === false) {
                throw new Exception('添加失败');
            }
            $lastId     = $model->getLastInsID();

            if ($flow['status'] == 1) {//固定审批
                //发送审批通知
                Flow::sendStepRecord($flow,Flow::ACHIEVEMENT_STATUS, $lastId);
            } else {//发起人自选 依次审批
                $staff_id   = explode(',', $params['flow_staff_ids'])[0];
                if ($staff_id) {
                    ExamineRecord::addExaminse(ExamineRecord::ACHIEVEMENT_TYPE, $lastId, $staff_id);
                }
            }
            Db::commit();;
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('修改成功,请等待审批人审核！');
    }

    //业绩修改历史表
    public function editRecords()
    {
        $department_id = input('department_id');
        $year = input('year', date('Y'), 'intval');
        $status = input('status', 1);//1销售（目标）2回款（目标） 3 获客  4拜访
        $limit = input("limit/d", 10);
        $staff_id = input('staff_id', $this->auth->id);
        $type = input('type', 3);//3员工 2团队
        $where = [];
        if ($department_id) {
            $where['department_id'] = $department_id;
        }
        $where['year'] = $year;
        $where['status'] = $status;

        $model = new AchievementRecords();

        $list = $model->where([
            'type' => $type,
            'obj_id' => $staff_id
        ])->where($where)->with(['staff'])->order('id desc')->paginate($limit);

        $this->success('请求成功', $list);
    }


    //获取修改业绩详情表
    public function getRecordsDetail()
    {
        $id = input('id');
        $model = new AchievementRecords();

        $records = $model->where([])->where([
            'id' => $id
        ])->with(['staff'])->find();
        if (empty($records)) {
            $this->error('记录不存在');
        }

        if ($records['check_status'] == 0 || $records['check_status'] == 1) {
            $records['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::ACHIEVEMENT_TYPE, $id);
        } else {
            $records['is_examine'] = 0;
        }
        //标记通知已读
        Message::setRead(Message::ACHIEVEMENT_TYPE, $id, $this->auth->id);
        $this->success('请求成功', $records);
    }


}
